﻿using MySql.Data.MySqlClient;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

public class RealTimeFileMonitor
{
    private readonly string _directoryPath;
    private FileSystemWatcher _watcher;
    private CancellationTokenSource _cancellationTokenSource;
    private Task _monitorTask;
    private int _fcount = 0; // 计数器变量
    private readonly object _lockObject = new object(); // 线程同步锁
    private const string connectionString = "Server=localhost;Port=3306;Database=screenpic;Uid=root;Pwd=hjj1019583787;";
    public string SavePicBox { get; set; }  // 需外部设置图片存储路径

    public RealTimeFileMonitor(string directoryPath, string savepicbox)
    {
        SavePicBox = savepicbox;
        _directoryPath = directoryPath;
        _cancellationTokenSource = new CancellationTokenSource();
    }

    // 启动实时文件监控
    public void StartMonitoring()
    {
        if (!Directory.Exists(_directoryPath))
        {
            MessageBox.Show($"监控路径不存在: {_directoryPath}");
            return;
        }

        // 初始化文件系统监控器
        _watcher = new FileSystemWatcher
        {
            Path = _directoryPath,
            Filter = "删除记录*.txt",              // 监控以"删除记录"开头的txt文件
            NotifyFilter = NotifyFilters.FileName, // 只监听文件名变化
            EnableRaisingEvents = true
        };

        // 注册文件创建事件
        _watcher.Created += OnFileCreated;

        // 启动后台任务处理初始文件
        _monitorTask = Task.Run(ProcessExistingFiles, _cancellationTokenSource.Token);
        Console.WriteLine($"实时监控已启动，路径: {_directoryPath}");
    }

    // 停止监控
    public void StopMonitoring()
    {
        _cancellationTokenSource.Cancel();
        _watcher?.Dispose();

        if (_monitorTask != null)
        {
            _monitorTask.Wait(TimeSpan.FromSeconds(5));
        }

        _cancellationTokenSource.Dispose();
        Console.WriteLine("实时监控已停止");
    }

    // 处理新创建的文件（实时事件响应）
    private void OnFileCreated(object sender, FileSystemEventArgs e)
    {
        try
        {
            // 确保文件已完全创建（避免文件正在写入时操作）
            Thread.Sleep(200);
            RenameFileIfNeeded(e.FullPath);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"处理新文件时出错: {e.FullPath}, 错误: {ex.Message}");
        }
    }

    // 处理启动时已存在的文件
    private async Task ProcessExistingFiles()
    {
        try
        {
            while (!_cancellationTokenSource.Token.IsCancellationRequested)
            {
                string[] files = Directory.GetFiles(_directoryPath, "删除记录*.txt");
                foreach (string file in files)
                {
                    RenameFileIfNeeded(file);
                }

                // 只执行一次初始检查
                break;
            }
        }
        catch (OperationCanceledException)
        {
            // 线程取消是正常情况
        }
        catch (Exception ex)
        {
            Console.WriteLine($"初始化文件检查出错: {ex.Message}");
        }
    }

    // 功能：打开这个文件（删除记录），然后把里面的记录从数据库删除，文件里的记录每一行就是一个文件名，从数据库找到文件名并删除，然后把本地图片也删除
    //  本地文件夹路径在SavePicBox里，假设数据库已经连接
    private void RenameFileIfNeeded(string filePath)
    {
        string fileName = Path.GetFileName(filePath);
        if (fileName.StartsWith("删除记录") && !fileName.StartsWith("F"))
        {
            lock (_lockObject)
            {
                _fcount++;
                string newFileName = $"F{_fcount}{fileName}";
                string newFilePath = Path.Combine(Path.GetDirectoryName(filePath), newFileName);

                try
                {
                    File.Move(filePath, newFilePath);
                    Console.WriteLine($"文件已重命名: {fileName} -> {newFileName} (Fcount={_fcount})");

                    ProcessDeleteRecordFile(newFilePath);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"重命名文件时出错: {filePath} -> {newFilePath}, 错误: {ex.Message}");
                }
            }
        }
    }

    private void ProcessDeleteRecordFile(string deleteRecordPath)
    {
        try
        {
            string[] fileNames = File.ReadAllLines(deleteRecordPath);

            foreach (var line in fileNames)
            {
                string targetFileName = line.Trim();
                if (string.IsNullOrEmpty(targetFileName)) continue;

                try
                {
                    // 1. 删除数据库记录
                    bool dbDeleteSuccess = DeleteRecordFromDatabase(targetFileName);
                    if (!dbDeleteSuccess)
                    {
                        Console.WriteLine($"数据库记录删除失败，跳过文件删除：{targetFileName}");
                        continue;
                    }

                    // 2. 删除本地图片文件
                    string imagePath = Path.Combine(SavePicBox, targetFileName);
                    if (File.Exists(imagePath))
                    {
                        File.Delete(imagePath);
                        Console.WriteLine($"本地图片删除成功：{imagePath}");
                    }
                    else
                    {
                        Console.WriteLine($"本地图片不存在：{imagePath}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"处理记录 {targetFileName} 时出错: {ex.Message}");
                }
            }
        }
        catch (IOException ex)
        {
            Console.WriteLine($"读取删除记录文件失败: {deleteRecordPath}, 错误: {ex.Message}");
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine($"无权限访问文件: {deleteRecordPath}, 错误: {ex.Message}");
        }
    }

    private bool DeleteRecordFromDatabase(string fileName)
    {
        const string sql = "DELETE FROM screenshots WHERE file_name = @FileName";

        using (var connection = new MySqlConnection(connectionString))
        {
            try
            {
                connection.Open();
                using (var command = new MySqlCommand(sql, connection))
                {
                    command.Parameters.AddWithValue("@FileName", fileName);
                    int rowsAffected = command.ExecuteNonQuery();
                    return rowsAffected > 0; // 返回是否实际删除了记录
                }
            }
            catch (MySqlException ex)
            {
                Console.WriteLine($"数据库操作失败（错误码：{ex.Number}）: {ex.Message}");
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"数据库操作异常: {ex.Message}");
                return false;
            }
        }
    }
}
